﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplicationC
{
    public partial class Function : System.Web.UI.Page
    {
        //public string userName = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            string localhost = string.Format("http://{0}:{1}/", Request.Url.Host, Request.Url.Port);
            //如果在此子系统中有Session
            if (!string.IsNullOrWhiteSpace(Session["userid"]?.ToString()) 
                && !string.IsNullOrWhiteSpace(Session["token"]?.ToString())
                && CheckOnline() > 0)
            {
                //检测正常登录
            }
            else
            {
                //跳转到登录页
                string loginUrl = string.Format("{0}login", localhost);
                Response.Redirect(loginUrl);
            }
        }

        public int CheckOnline()
        {
            int isOnline = 0;
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(ConfigHelper.APIHost);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("appliation/json"));
            UserInfo user = new UserInfo()
            {
                AppKey = ConfigHelper.AppKey,
                AppSecret = ConfigHelper.AppSecret,
                Ip = Request.UserHostAddress,
                UserId = Session["userid"].ToString(),
                Token = Session["token"].ToString(),
            };
            HttpResponseMessage response = client.PostAsJsonAsync("api/sso/checkonline", user).Result;
            if (response.IsSuccessStatusCode)
            {
                Result obj = new Result();
                var result = response.Content.ReadAsAsync<Result>().Result;
                if (result.Code == 0)
                {
                    isOnline = 1;
                }
                else if (result.Code == 2)
                {
                    isOnline = 2;
                }
            }
            return isOnline;
        }
    }
}